package cn.zero.letaomallspringboot.config;

import cn.zero.letaomallspringboot.filter.JwtAuthenticationFilter;
import cn.zero.letaomallspringboot.filter.RequestLoggingFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig {
    @Value("${cors.allowed-origins:http://localhost:5173}")
    private String[] allowedOrigins;

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")  // 允许所有路径（如 /admin/**）
                        .allowedOriginPatterns(allowedOrigins)  // 匹配浏览器 Origin，支持开发/生产
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH")  // 允许方法，包括预检
                        .allowedHeaders("*")  // 允许所有头（如 Content-Type, Authorization）
                        .allowCredentials(true)  // 允许 Cookie/Token（sa-token 需）
                        .maxAge(3600);  // 预检缓存 1 小时
            }
        };
    }

    @Bean
    public FilterRegistrationBean<JwtAuthenticationFilter> jwtFilter() {
        FilterRegistrationBean<JwtAuthenticationFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new JwtAuthenticationFilter());
        registration.addUrlPatterns("/*");
        registration.setOrder(1);
        registration.setName("jwtFilter");
        return registration;
    }

    @Bean
    public FilterRegistrationBean<RequestLoggingFilter> requestLoggingFilter() {
        FilterRegistrationBean<RequestLoggingFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new RequestLoggingFilter());
        registration.addUrlPatterns("/*");
        registration.setOrder(0); // ensure request is logged before other filters
        registration.setName("requestLoggingFilter");
        return registration;
    }
}
